package com.lhweb.springsecurity.security;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;

public class CustomJdbcDaoImpl extends JdbcDaoImpl implements IUserService {
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private SaltSource saltSource;
	
	/**
	 * 修改用户密码
	 */
	@Override
	public void changePassword(String username, String password) {
		UserDetails user = loadUserByUsername(username);
		String encodedPassword = passwordEncoder.encodePassword(password, saltSource.getSalt(user));

		getJdbcTemplate().update(
				"UPDATE users set password = ? WHERE username = ?", encodedPassword,
				username);
	}
	
	/**
	 * 新建用户
	 */
	@Override
	protected UserDetails createUserDetails(String username,
			UserDetails userFromUserQuery,
			List<GrantedAuthority> combinedAuthorities){
		String returnUsername = userFromUserQuery.getUsername();
		if(!isUsernameBasedPrimaryKey()){
			returnUsername = username;
		}
		return new SaltedUser(returnUsername,
				userFromUserQuery.getPassword(),userFromUserQuery.isEnabled(),
				true,true,true,combinedAuthorities,
				((SaltedUser)userFromUserQuery).getSalt());
	}
	
	/**
	 * 根据用户名查找用户
	 */
	@Override
	public List<UserDetails> loadUsersByUsername(String username) {
		return getJdbcTemplate().query(getUsersByUsernameQuery(), new String[]{username},
				new RowMapper<UserDetails>(){
					@Override
					public UserDetails mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						String username = rs.getString("username");
						String password = rs.getString("password");
						boolean enabled = rs.getBoolean("enabled");
						String salt = rs.getString("salt");
						return new SaltedUser(username,password,enabled,true,true,true,
								AuthorityUtils.NO_AUTHORITIES,salt);
					}
			
		});
	}
	
}
